const express = require('express');
const router = express.Router();
const { Course, User, Like } = require('../models');
const { failure, success } = require('../utils/responses');
const { NotFoundError } = require('../utils/errors');

//点赞和取消赞
router.post('/', async (req, res) => {
    try {
        const userId = req.userId;
        const { courseId } = req.body;

        const course = await Course.findByPk(courseId);
        if (!course) {
            throw new NotFoundError('课程不存在');
        }

        //判断是否已经点赞
        const like = await Like.findOne({
            where: {
                courseId,
                userId
            }
        });
        if (!like) {
            await Like.create({ courseId, userId })
            //increment 自增
            await course.increment('likesCount')
            success(res, '点赞成功')
        } else {
            await like.destroy()
            //decrement 自减
            await course.decrement('likesCount')
            success(res, '取消点赞成功')
        }
    } catch (error) {
        failure(res, error);
    }
})

//查询用户点赞的课程
router.get('/', async (req, res) => {
    try {
        //多对多关联中使用limit等参数作为分页会报错
        const query = req.query
        const currentPage = parseInt(query.currentPage) || 1
        const pageSize = parseInt(query.pageSize) || 10
        const offset = (currentPage - 1) * pageSize

        //查询当前用户
        const user = await User.findByPk(req.userId)

        //查询当前用户点赞的课程
        /*
            使用在模型中定义的关系别名，前面加上get，就可以调用这个方法，如getLikedCourses
                使用这个方法可以记录分页的参数，但不能记录一共有多少条参数
        */
        const courses = await user.getLikeCourses({
            //表示关联表数据不查询
            joinTableAttributes: [],
            attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset,
        })

        const count=await user.countLikeCourses()
        success(res, '查询当前用户点赞的课程成功',{ 
            courses,
            pagination:{
                total:count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error);
    }
})

module.exports = router;